﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.GISClient;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Server;
using System.Threading;

namespace ClientApplication
{
    public partial class MapServiceManager : Form
    {
        //stop or start操作结果
        private bool methodResult = false;
        //进度条完成标记位
        private bool processBarComplete = false;
        //进度条
        ProcessBarWin myProcessBar;
        //GISServerMng对象，从构造函数中获得
        GISServerMng pSerMgn = null;

        public GISServerMng PSerMgn
        {
            get { return pSerMgn; }
            set { pSerMgn = value; }
        }
        //编辑模式下获取ServerAdmin对象，用来控制Server服务的状态
        IServerObjectAdmin pServerAdmin;

        public IServerObjectAdmin PServerAdmin
        {
            get { return pServerAdmin; }
            set { pServerAdmin = value; }
        }
        //编辑模式下被选中的configuration
        IServerObjectConfiguration selectedServerConfig = null;

        public IServerObjectConfiguration SelectedServerConfig
        {
            get { return selectedServerConfig; }
            set { selectedServerConfig = value; }
        }
        //编辑模式下保存所有的configuration
        private List<IServerObjectConfiguration> serverConfigList = null;

        public List<IServerObjectConfiguration> ServerConfigList
        {
            get { return serverConfigList; }
            set { serverConfigList = value; }
        }

        //编辑模式下选中的Configuration对应的status
        IServerObjectConfigurationStatus selectedConfigStatus = null;

        public IServerObjectConfigurationStatus SelectedConfigStatus
        {
            get { return selectedConfigStatus; }
            set { selectedConfigStatus = value; }
        }
        //选中加载的Server在AGSServerNameObjectList中的序号
        private int selectedIndex;

        public int SelectedIndex
        {
            get { return selectedIndex; }
            set { selectedIndex = value; }
        }

        //标记是否以编辑模式进入
        private bool editAble;

        public bool EditAble
        {
            get { return editAble; }
            set { editAble = value; }
        }
        //保存所有的ServerObjName
        private List<IAGSServerObjectName> serverObjNameList = null;

        public List<IAGSServerObjectName> ServerObjNameList
        {
            get { return serverObjNameList; }
            set { serverObjNameList = value; }
        }


        //选中的ServerObjName
        IAGSServerObjectName selectedServerObj = null;

        public IAGSServerObjectName SelectedServerObj
        {
            get { return selectedServerObj; }
            set { selectedServerObj = value; }
        }

        //非编辑模式下获取的ServerConnection
        IAGSServerConnection customerConn = null;

        public IAGSServerConnection CustomerConn
        {
            get { return customerConn; }
            set { customerConn = value; }
        }
        ////选中的MapServer获得图层
        //IMapServerLayer pMapServerLayer = null;

        //public IMapServerLayer PMapServerLayer
        //{
        //    get { return pMapServerLayer; }
        //    set { pMapServerLayer = value; }
        //}


        /// <summary>
        /// 带参数的构造函数,非编辑模式的构造函数
        /// </summary>
        /// <param name="serverAdmin"></param>
        /// <param name="isEdit"></param>
        public MapServiceManager(IAGSServerConnection customerConn, bool isEdit)
        {
            InitializeComponent();
            CustomerConn = customerConn;
            //获得编辑模式标记位
            this.EditAble = isEdit;
            //初始化非编辑模式的serverObjNameList
            serverObjNameList = new List<IAGSServerObjectName>();

            //this.backgroundWorker_start = null;

            //this.backgroundWorker_stop = null;

            //this.backgroundWorker_processbar = null;
        }

        /// <summary>
        /// 带参数的构造函数,编辑模式的构造函数
        /// </summary>
        /// <param name="PServerAdmin"></param>
        /// <param name="isEdit"></param>
        public MapServiceManager(IServerObjectAdmin pServerAdmin, bool isEdit)
        {
            InitializeComponent();
            PServerAdmin = pServerAdmin;
            //获得编辑模式标记位
            this.EditAble = isEdit;
            //初始编辑模式的configurationlist
            serverConfigList = new List<IServerObjectConfiguration>();

            //this.backgroundWorker_start = null;

            //this.backgroundWorker_stop = null;

            //this.backgroundWorker_processbar = null;

        }

        /// <summary>
        /// 初始化ServerObjListView的Title
        /// 根据是否为编辑模式进行不同处理，
        /// 编辑模式获取configurations
        /// 非编辑模式获取AGSServerObjNameList
        /// </summary>
        private void InitSerListView()
        {
            // Set the view to show details.
            listView_server.View = View.Details;
            // Select the item and subitems when selection is made.
            listView_server.FullRowSelect = true;
            // Display grid lines.
            listView_server.GridLines = true;
            // Create columns for the items and subitems. 
            // Width of -2 indicates auto-size.
            listView_server.Columns.Add("Id", 50, HorizontalAlignment.Left);
            listView_server.Columns.Add("Name", -2, HorizontalAlignment.Left);
            if (EditAble)
            {
                //编辑模式下，获取configuration
                getConfigurations();
                //填充server listview
                for (int i = 0; i < ServerConfigList.Count; i++)
                {
                    ListViewItem lvi = new ListViewItem(i.ToString());
                    lvi.SubItems.Add(serverConfigList.ElementAt(i).Name);
                    listView_server.Items.Add(lvi);
                }
            }
            else
            {
                //非编辑模式，填充ListView
                getAGSServerObjNameList();


                for (int i = 0; i < ServerObjNameList.Count; i++)
                {
                    //if (ServerObjNameList.ElementAt(i).Type.Equals("MapServer") || ServerObjNameList.ElementAt(i).Type.Equals("GPServer") || ServerObjNameList.ElementAt(i).Type.Equals("GeometryServer"))
                    //{
                    ListViewItem lvi = new ListViewItem(i.ToString());
                    lvi.SubItems.Add(ServerObjNameList.ElementAt(i).Name);
                    listView_server.Items.Add(lvi);
                    //}

                }
            }

        }
        /// <summary>
        /// 初始化InfoListView的函数
        /// </summary>
        private void InitInfoListView()
        {
            listView_info.View = View.Details;

            listView_info.FullRowSelect = true;

            listView_info.GridLines = true;

            listView_info.Columns.Add("Item", 200, HorizontalAlignment.Center);

            listView_info.Columns.Add("Value", -2, HorizontalAlignment.Left);
        }

        /// <summary>
        /// 窗体的Load事件处理函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MapServiceManager_Load(object sender, EventArgs e)
        {
            //初始化ListView
            InitSerListView();
            InitInfoListView();
            //
            if (EditAble)
            {
                //编辑模式的初始化
                //MessageBox.Show("编辑模式");
                button_ok.Text = "Start";
                button_cancle.Text = "Stop";
            }
            else
            {
                //非编辑模式的初始化
                //MessageBox.Show("非编辑模式");
                button_ok.Text = "Load";
                //设置load按钮的DialogResult为ok属性
                button_ok.DialogResult = DialogResult.OK;
                button_cancle.Text = "Cancel";
                button_cancle.DialogResult = DialogResult.Cancel;
            }
        }


        #region listview选项变化处理函数
        /// <summary>
        /// 用来处理listview选中项变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listView_server_SelectedIndexChanged(object sender, EventArgs e)
        {
            //在SelectedChanged后，必须清空InfoListView
            listView_info.Items.Clear();
            //获得选中的IndexId
            SelectedIndex = Convert.ToInt32(this.listView_server.FocusedItem.SubItems[0].Text);
            //首先要判断有没有项被选中变蓝，如果不判断那么用到SelectedItem[i]时会因为没有合适结果报错
            if (this.listView_server.SelectedItems.Count > 0)
            {
                //根据是否为编辑模式进行不同的处理
                if (EditAble)
                {
                    //编辑模式的处理
                    SelectedServerConfig = ServerConfigList.ElementAt(SelectedIndex);
                    ListViewItem lvi;
                    //添加Name属性
                    lvi = new ListViewItem("Name");
                    lvi.SubItems.Add(SelectedServerConfig.Name);
                    listView_info.Items.Add(lvi);
                    //添加TypeName属性
                    lvi = new ListViewItem("TypeName");
                    lvi.SubItems.Add(SelectedServerConfig.TypeName);
                    listView_info.Items.Add(lvi);
                    //添加MinInstances属性
                    lvi = new ListViewItem("MinInstances");
                    lvi.SubItems.Add(SelectedServerConfig.MinInstances.ToString());
                    listView_info.Items.Add(lvi);
                    //添加MaxInstances属性
                    lvi = new ListViewItem("MaxInstances");
                    lvi.SubItems.Add(SelectedServerConfig.MaxInstances.ToString());
                    listView_info.Items.Add(lvi);
                    //添加IsPooled属性
                    lvi = new ListViewItem("IsPooled");
                    lvi.SubItems.Add(SelectedServerConfig.IsPooled ? "是" : "否");
                    listView_info.Items.Add(lvi);
                    //添加StartupType属性
                    lvi = new ListViewItem("StartupType");
                    lvi.SubItems.Add(SelectedServerConfig.StartupType.ToString());
                    listView_info.Items.Add(lvi);
                    //添加Description属性
                    lvi = new ListViewItem("Description");
                    lvi.SubItems.Add(SelectedServerConfig.Description);
                    listView_info.Items.Add(lvi);


                    //添加Status属性
                    selectedConfigStatus = PServerAdmin.GetConfigurationStatus(SelectedServerConfig.Name, SelectedServerConfig.TypeName);
                    //添加InstanceCount属性
                    lvi = new ListViewItem("InstanceCount");
                    lvi.SubItems.Add(selectedConfigStatus.InstanceCount.ToString());
                    listView_info.Items.Add(lvi);
                    //添加InstanceInUseCount属性
                    lvi = new ListViewItem("InstanceInUseCount");
                    lvi.SubItems.Add(selectedConfigStatus.InstanceInUseCount.ToString());
                    listView_info.Items.Add(lvi);
                    //添加Status属性
                    lvi = new ListViewItem("Status");
                    lvi.SubItems.Add(selectedConfigStatus.Status.ToString());
                    listView_info.Items.Add(lvi);
                }
                else
                {
                    //非编辑模式的处理
                    //MessageBox.Show("Select Changed");
                    selectedServerObj = ServerObjNameList.ElementAt(SelectedIndex);
                    ListViewItem lvi;
                    //添加Name属性
                    lvi = new ListViewItem("Name");
                    lvi.SubItems.Add(selectedServerObj.Name);
                    listView_info.Items.Add(lvi);
                    //添加Type属性
                    lvi = new ListViewItem("Type");
                    lvi.SubItems.Add(selectedServerObj.Type);
                    listView_info.Items.Add(lvi);
                    //添加Url属性
                    lvi = new ListViewItem("Url");
                    lvi.SubItems.Add(selectedServerObj.URL);
                    listView_info.Items.Add(lvi);
                    //添加ConnectionUrl
                    lvi = new ListViewItem("AGSServerConnectionUrl");
                    lvi.SubItems.Add(selectedServerObj.AGSServerConnectionName.ToString());
                    listView_info.Items.Add(lvi);
                }
            }
        #endregion


        }

        #region 按钮事件处理函数
        /// <summary>
        /// 处理button_ok的事件函数
        /// 当处于编辑模式，为configuration的start处理
        /// 当处于非编辑模式，为serverObj的load处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_ok_Click(object sender, EventArgs e)
        {
            if (EditAble)
            {
                //MessageBox.Show(SelectedServerConfig.Name);
                //编辑模式的Start处理事件
                if (this.listView_server.SelectedItems.Count > 0)
                {
                    //判断当前服务的状态是否已经是启动
                    if (SelectedConfigStatus.Status.Equals(esriConfigurationStatus.esriCSStarted))
                    {
                        MessageBox.Show("当前服务已启动", "错误操作", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        //this.backgroundWorker_start.Dispose();
                        //this.backgroundWorker_start = new BackgroundWorker();
                        //启动服务启动线程
                        this.backgroundWorker_start.RunWorkerAsync();

                        //MessageBox.Show("停止服务");
                        myProcessBar = new ProcessBarWin();
                        myProcessBar.Text = "正在启动服务请耐心等待";
                        //backgroundWorker_processbar.WorkerReportsProgress = true;
                        //设置进度条线程支持异步取消
                        //backgroundWorker_processbar.WorkerSupportsCancellation = true;
                        //this.backgroundWorker_processbar.RunWorkerAsync();
                        myProcessBar.ShowDialog();

                    }


                }
                else
                {
                    MessageBox.Show("错误操作", "请选择要启动的服务", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                //非编辑模式的Load处理事件
                if (this.listView_server.SelectedItems.Count > 0)
                {
                    //获得选中对象
                    //selectedServerObj = ServerObjNameList.ElementAt(Convert.ToInt32(this.listView_server.FocusedItem.SubItems[0].Text));
                    //判断选中对象的Type是不是MapServer
                    if (selectedServerObj.Type.Equals("MapServer"))
                    {
                        //SelectedIndex = Convert.ToInt32(this.listView_server.FocusedItem.SubItems[0].Text);
                        //selectedServerObj = ServerObjNameList.ElementAt(SelectedIndex);
                        //MessageBox.Show(selectedServerObj.Name);
                    }
                    else
                    {
                        MessageBox.Show("请选择MapServer类型的服务", "类型错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }

        }
        /// <summary>
        /// 处理button_cancel的事件函数
        /// 当处于编辑模式，为configuration的stop处理
        /// 当处于非编辑模式，为cancel事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_cancle_Click(object sender, EventArgs e)
        {
            if (EditAble)
            {
                //编辑模式的Stop处理事件
                if (this.listView_server.SelectedItems.Count > 0)
                {
                    //判断当前服务的状态是否已经是停止
                    if (SelectedConfigStatus.Status.Equals(esriConfigurationStatus.esriCSStopped))
                    {
                        MessageBox.Show("当前服务已停止","错误操作",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    }
                    else
                    {
                        //this.backgroundWorker_stop.Dispose();

                        //this.backgroundWorker_stop = new BackgroundWorker();
                        //启动停止服务线程
                        this.backgroundWorker_stop.RunWorkerAsync();

                        //MessageBox.Show("停止服务");
                        myProcessBar = new ProcessBarWin();
                        myProcessBar.Text = "正在停止服务请耐心等待";
                        //backgroundWorker_processbar.WorkerReportsProgress = true;
                        //设置进度条线程支持异步取消
                        //backgroundWorker_processbar.WorkerSupportsCancellation = true;
                        //this.backgroundWorker_processbar.RunWorkerAsync();
                        myProcessBar.ShowDialog();
                    }


                }
                else
                {
                    MessageBox.Show("错误操作","请选择要停止的服务", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
            else
            {
                //非编辑模式的cancel事件
                this.Close();
            }
        }

        #endregion


        #region 停止服务线程处理过程
        private void backgroundWorker_stop_DoWork(object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(1000);
            //MessageBox.Show("start backgroundWorker_stop_DoWork");
            backgroundWorker_processbar.ReportProgress(10);
            Thread.Sleep(1000);
            stopServer(SelectedServerConfig.Name, SelectedServerConfig.TypeName);
            backgroundWorker_processbar.ReportProgress(80);
            Thread.Sleep(1000);
            //MessageBox.Show("backgroundWorker_stop_DoWork complete");
        }

        private void backgroundWorker_stop_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //string name = SelectedServerObj.Name;
            //string type = SelectedServerObj.Type;
            //MessageBox.Show(PServerAdmin.GetConfigurationStatus(SelectedServerConfig.Name, SelectedServerConfig.TypeName).ToString());
            methodResult = true;
            //MessageBox.Show("stop ok");

            backgroundWorker_processbar.ReportProgress(90);
            Thread.Sleep(1000);
            backgroundWorker_processbar.ReportProgress(100);
            Thread.Sleep(1000);
            //处理进度条结束事件
            //关闭进度条子窗体
            myProcessBar.Close();
            // MessageBox.Show("进度条完成");
            //释放进度条窗体引用
            myProcessBar = null;

            //设置进度条完成标记变量为True
            processBarComplete = true;

            //更新listview
            refreashInfoListView();

            //释放资源
            this.backgroundWorker_stop.Dispose();
        }
        private void stopServer(string name, string type)
        {
            PServerAdmin.StopConfiguration(name, type);
        }

        #endregion


        #region 进度条子线程控制
        //private void countTheTime()
        //{
        //    if (!backgroundWorker_processbar.CancellationPending)
        //    {
        //        int initialValue = 100;
        //        for (int count = 0; count < initialValue; count = count + 2)
        //        {
        //            Thread.Sleep(100);
        //            backgroundWorker_processbar.ReportProgress(count);
        //        }
        //    }
        //}

        //private void backgroundWorker_processbar_DoWork(object sender, DoWorkEventArgs e)
        //{
        //    countTheTime();
        //}

        private void backgroundWorker_processbar_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (!backgroundWorker_processbar.CancellationPending)
            {
                //当进度条没有被其他线程取消时才进行计算
                myProcessBar.Increase(e.ProgressPercentage);
            }
        }

        //private void backgroundWorker_processbar_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        //{
        //    //关闭进度条子窗体
        //    myProcessBar.Close();
        //    // MessageBox.Show("进度条完成");
        //    //释放进度条窗体引用
        //    myProcessBar = null;

        //    //设置进度条完成标记变量为True
        //    processBarComplete = true;
        //}
        #endregion

        #region 获取serverList listview对应的list对象
        /// <summary>
        /// 用来获取AGSServerObjNameList的方法
        /// 直接赋值给this的成员变量
        /// 该成员变脸已经在窗体的构造方法中初始化
        /// </summary>
        private void getAGSServerObjNameList()
        {
            //this.serverObjNameList = new List<IAGSServerObjectName>();

            IAGSEnumServerObjectName pServerObjectNames = CustomerConn.ServerObjectNames;
            //start the enumeration at the begining            
            pServerObjectNames.Reset();

            IAGSServerObjectName agsServerObjectName = pServerObjectNames.Next();
            while (agsServerObjectName != null)
            {
                //MessageBox.Show(agsServerObjectName.ToString());
                ServerObjNameList.Add(agsServerObjectName);
                agsServerObjectName = pServerObjectNames.Next();
            }
        }
        /// <summary>
        /// 用来获取configurationList的方法
        /// 直接赋值给this的成员变量
        /// 该成员变脸已经在窗体的构造方法中初始化
        /// </summary>
        private void getConfigurations()
        {
            //get the ServerObjectConfiguration enumeration
            IEnumServerObjectConfiguration pServerObjectConfigurations = PServerAdmin.GetConfigurations();
            //start the enumeration at the begining
            pServerObjectConfigurations.Reset();
            //get the ServerObjectConfiguration
            IServerObjectConfiguration serverObjectConfiguration = pServerObjectConfigurations.Next();
            while (serverObjectConfiguration != null)
            {
                ServerConfigList.Add(serverObjectConfiguration);
                serverObjectConfiguration = pServerObjectConfigurations.Next();
            }
        }
        #endregion


        #region 启动服务线程
        private void backgroundWorker_start_DoWork(object sender, DoWorkEventArgs e)
        {
            //MessageBox.Show("start backgroundWorker_start_DoWork");
            Thread.Sleep(1000);
            backgroundWorker_processbar.ReportProgress(10);
            Thread.Sleep(1000);
            startServer(SelectedServerConfig.Name, SelectedServerConfig.TypeName);
            backgroundWorker_processbar.ReportProgress(80);
            Thread.Sleep(1000);
            //MessageBox.Show("backgroundWorker_start_DoWork complete");

        }

        private void backgroundWorker_start_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            methodResult = true;
            //MessageBox.Show("start ok");
            backgroundWorker_processbar.ReportProgress(90);
            Thread.Sleep(1000);
            backgroundWorker_processbar.ReportProgress(100);
            Thread.Sleep(1000);
            //处理进度条结束事件
            //关闭进度条子窗体
            myProcessBar.Close();
            // MessageBox.Show("进度条完成");
            //释放进度条窗体引用
            myProcessBar = null;

            //设置进度条完成标记变量为True
            processBarComplete = true;
            //刷新listview
            refreashInfoListView();
            //释放资源
            this.backgroundWorker_start.Dispose();


        }
        private void startServer(string name, string type)
        {
            PServerAdmin.StartConfiguration(name, type);
        }
        #endregion


        /// <summary>
        /// 用以在启动或者停止服务后刷新InfoListView
        /// </summary>
        private void refreashInfoListView()
        {
            //listView_server.Items[0].Selected = true;
            //MessageBox.Show("refreashInfoListView OK");

            listView_server.SelectedItems.Clear();

            listView_server.Items[SelectedIndex].Selected = true;

            listView_server.Items[SelectedIndex].Focused = true;
        }
    }
}
